package com.woniu.utils;

import com.jcraft.jsch.*;
import java.io.*;

public class SSHUtils {
    private static final int SSH_PORT = 22;
    private static final int TIMEOUT = 30000;

    public static String executeRemoteCommand(String host, String username,
                                              String password, String command)
            throws JSchException, IOException {
        Session session = null;
        ChannelExec channel = null;
        StringBuilder output = new StringBuilder();

        try {
            JSch jsch = new JSch();
            session = jsch.getSession(username, host, SSH_PORT);
            session.setPassword(password);
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect(TIMEOUT);

            channel = (ChannelExec) session.openChannel("exec");
            channel.setCommand(command);
            channel.connect();

            try (InputStream in = channel.getInputStream();
                 BufferedReader reader = new BufferedReader(new InputStreamReader(in))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    output.append(line).append("\n");
                }
            }
        } finally {
            if (channel != null) channel.disconnect();
            if (session != null) session.disconnect();
        }
        return output.toString();
    }
}
